package com.blockmeta.bbs.businesslibrary.websocket;


import android.text.TextUtils;
import android.util.SparseArray;

import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.base.eventbus.EventBusBase;
import com.blockmeta.bbs.businesslibrary.business.DataManager;
import com.blockmeta.bbs.businesslibrary.pojo.CoinsDetailPOJO;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import buf.Kline;
import buf.Return;

public class Symbol extends EventBusBase implements IConnect, Comparable<Symbol>
{


	protected Market m_market; // 商品儲存的Market

	protected String m_strCode; //合并code和交易所名称
	protected String m_strShortName; //
	protected volatile String m_strName; // 名稱
	protected String m_strSubName;
	protected String m_strSesName;
	protected String m_strTickTable;
	protected String m_strTUnit;



	protected int m_nTradeDate;
	protected double m_dbPreClose;
	protected SortTable<Integer, String> m_SortTableQuote; // 行情表
	protected SparseArray<AppDefine.ColorDef> m_arColorDef; // 漲跌表
	protected SparseArray<AppDefine.ColorDef> m_arBgColorDef; // 漲跌背景顏色表
	protected Map<ChartData.ChartPeroid, ChartData> m_mapChartData; // ChartData Cache
	protected int m_nDigit; // 價格小數位數
	protected int m_nVolumnDigit; // 價格小數位數
	protected boolean m_bTradable;
	protected boolean m_isHkConnect;

	protected ReentrantReadWriteLock m_ChartLock;
	protected ReentrantReadWriteLock m_QuoteLock;
	private AtomicLong m_MarginRateTime = new AtomicLong();


	private boolean m_NeedQuoteUpdateChart = true;




	public Symbol(Market market, String code)
	{
		super();
		m_QuoteLock = new ReentrantReadWriteLock();
		m_ChartLock = new ReentrantReadWriteLock();
		m_strCode = code;
		m_dbPreClose = 0;
		m_strName = "";
		m_strSubName = "";
		m_nDigit = -1;
		m_nVolumnDigit = -1;
		initStmbol(market);
	}

	public static String makeSymbolCode(String code, String exchange)
	{
		if(TextUtils.isEmpty(code) || TextUtils.isEmpty(exchange))
			return "";
		return code.concat(".").concat(exchange);
	}


	protected void initStmbol(Market market)
	{
		m_market = market;

		m_strTUnit = "";

		m_SortTableQuote = new SortTable<Integer, String>();
		m_arColorDef = new SparseArray<AppDefine.ColorDef>(Fields.FieldCount);
		m_arBgColorDef = new SparseArray<AppDefine.ColorDef>(Fields.FieldCount);
		m_mapChartData = new ConcurrentHashMap<>();
		m_bTradable = true;

	}


	public Set<Integer> getAllFieldId()
	{
		return m_SortTableQuote.keySet();
	}


	public String getCode()
	{
		return m_strCode;
	}


	public String getShortName()
	{
		return "";
	}





	public String getName()
	{
		return m_strName;
	}


	public String getTickTableKey()
	{
		return m_strTickTable;
	}

	public String getTUnit()
	{
		return m_strTUnit;
	}



	public String getDollar()
	{

		return "";
//		return getMarket().getDollar();
	}

	public int getTradeDate()
	{
		return m_nTradeDate;
	}

	public boolean isTradable()
	{
		return m_bTradable;
	}

	public boolean isNeedQuoteUpdateChart()
	{
		return m_NeedQuoteUpdateChart;
	}


	public boolean exist(Integer fieldID)
	{
		return m_SortTableQuote.exist(fieldID);
	}

	public Market getMarket()
	{
		return m_market;
	}

	public String getExchange() {

		int dot = m_strCode.indexOf('.');

		if (dot != -1)
		{
			return m_strCode.substring(dot + 1);
		}
		return "";
	}


	public String getSymbolCode()
	{
		int dot = m_strCode.indexOf('.');

		if (dot != -1)
		{
			return m_strCode.substring(0, dot);
		}
		return "";
	}

	public double getPriceClose()
	{
		if (m_dbPreClose == 0)
		{
			getQuote();
		}
		return m_dbPreClose;
	}

	public void getQuote()
	{

	}

	@Override
	public int compareTo(Symbol another)
	{
		return m_strCode.compareTo(another.getCode()) * -1;
	}

	@Override
	public void onConnectOK()
	{
		refresh();
	}

	@Override
	public void onConnectClose()
	{
	}

	public int getDigit()
	{
		return m_nDigit;
	}

	public int getVolumnDigit()
	{
		return m_nVolumnDigit;
	}


	public void processChartUpdate(Return.NormalReturn packet) {

		if(packet == null || packet.getExtraMap() == null || packet.getExtraMap().get("time_type") == null)
			return;
		String time_type = packet.getExtraMap().get("time_type");
		ChartData.ChartPeroid freq = ChartData.ChartPeroid.getChartType(time_type);
		ChartData chart = m_mapChartData.get(freq);

		if (chart == null)
		{
			chart = new com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData(this, freq);
			m_mapChartData.put(freq, chart);
		}

		if (m_nDigit < 0 && packet.getKlineList() != null && packet.getKlineList().getKlinesCount() > 0)
		{
			int maxPriceDigit = 0;
			int maxVolumnDigit = 0;
			for(Kline.KlineListItem klineListItem : packet.getKlineList().getKlinesList()){
				int digitPriceNumber = FormatUtil.getDigitNumber(String.valueOf(klineListItem.getClose()));
				if(maxPriceDigit < digitPriceNumber){
					maxPriceDigit = digitPriceNumber;
				}
				int digitVolumnNumber = FormatUtil.getDigitNumber(String.valueOf(klineListItem.getVol()));
				if(maxVolumnDigit < digitVolumnNumber){
					maxVolumnDigit = digitVolumnNumber;
				}
			}
			m_nDigit = maxPriceDigit; // 取得價格小數位數
			m_nVolumnDigit = maxVolumnDigit;
		}

		chart.processChartUpdate(packet);
	}

	public void processDepthUpdate(Return.NormalReturn packet) {

		if(packet == null || packet.getExtraMap() == null)
			return;
		ChartData chart = m_mapChartData.get(ChartData.ChartPeroid.DEPTH);

		if (chart == null)
		{
			chart = new ChartData(this, ChartData.ChartPeroid.DEPTH);
			m_mapChartData.put(ChartData.ChartPeroid.DEPTH, chart);
		}

		chart.processDepthUpdate(packet);
	}

	public void processQuoteUpdate(Return.NormalReturn packet) {

		if (packet == null || packet.getExtraMap() == null)
			return;
		CoinsDetailPOJO detailPOJO = new CoinsDetailPOJO(packet.getTickerData());

//		if (m_nDigit < 0 && detailPOJO != null && detailPOJO.getTicker() != null)
//		{
//			String price = detailPOJO.getTicker().getTicker().getLast();
//			m_nDigit = CommonLib.getDigitNumber(price); // 取得價格小數位數
//			String volumn = detailPOJO.getTicker().getTicker().getVolume();
//			m_nVolumnDigit = CommonLib.getDigitNumber(volumn);
//		}

		DataManager.getDataManager().getQuoteCenter().post(
				new QuoteCenter.Event_MemoryRefresh(this, detailPOJO));

	}

	// 重新查詢
	public void refresh()
	{
//		for (ChartData data : m_mapChartData.values())
//		{
//			if (data.getEventListener() != null)
//			{
//				data.query(null);
//			}
//		}
	}

	public ChartData queryChart(String key, ChartData.ChartPeroid freq)
	{
		com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData chart = m_mapChartData.get(freq);

		if (chart == null && freq != null)
		{
			try
			{
				m_ChartLock.writeLock().lock();
				chart = new com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData(this,freq);
				m_mapChartData.put(freq, chart);
			}
			finally
			{
				m_ChartLock.writeLock().unlock();
			}
		}

		chart.query(key, freq);

		return chart;
	}

	public void unregisterChart(String key, ChartData.ChartPeroid type)
	{
		ChartData chart = m_mapChartData.get(type);

		if (chart != null)
		{
			chart.unregisterChart(key, type);
		}
	}

	/**
	 *
	 * @param packet
	 */
	public void processTradeUpdate(Return.NormalReturn packet) {
		for (ChartData chart : m_mapChartData.values())
		{
			chart.processTradeUpdate(packet);
		}
	}
}
